package com.fumihiko.modules.job.task;

import com.fumihiko.common.utils.DateTimeUtil;
import com.fumihiko.modules.ca.service.UserAppinfoService;
import com.fumihiko.modules.ca.service.UserTokenService;
import com.fumihiko.modules.ca.vo.UserAppinfoVo;
import com.fumihiko.modules.ca.vo.UserTokenVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 测试定时任务(演示Demo，可删除)
 *
 * testTask为spring bean的名称
 *
 * @author devilzwy@gmail.com
 */
@Component("testTaskFor")
public class TestTaskFor implements ITask {
	//private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserAppinfoService userAppinfoService;
	@Autowired
	private UserTokenService userTokenService;


	@Override
	public void run(String params){
//		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//		HttpServletResponse response = servletRequestAttributes.getResponse();
//		HttpServletRequest request = servletRequestAttributes.getRequest();
		List<UserAppinfoVo> userAppinfoVoList = userAppinfoService.getUserAppinfoList();
		if(null != userAppinfoVoList){
			for(UserAppinfoVo userAppinfoVo : userAppinfoVoList){
				List<UserTokenVo> userTokenVoList = userTokenService.getUserTokenVoObj(userAppinfoVo.getAppId(), userAppinfoVo.getAppSecret());
				for(UserTokenVo userTokenVo: userTokenVoList){
					if(null != userTokenVo) {
						Long sec = DateTimeUtil.getTimeMinusToSec(DateTimeUtil.getCurrentTime(), userTokenVo.getExpirationTime());
						if (sec > 0) {
//							Cookie[] cookie = request.getCookies();
////							for (int i = 0; i < cookie.length; i++) {
////								Cookie cook = cookie[i];
////								if(cook.getValue().equalsIgnoreCase(userTokenVo.getAccessToken())){
////									Cookie cookie1 = new Cookie("token",null);
////									cookie1.setMaxAge(0); //设置立即删除
////									response.addCookie(cookie1);
////								}
////							}
							userTokenService.deleteUserTokenVoObj(userAppinfoVo.getAppId(), userAppinfoVo.getAppSecret(), userTokenVo.getAccessToken());
						}else{
							continue;
						}
					}
				}
			}
		}
		//System.out.println("我是定时任务");
	}
}
